#! /usr/bin/env escript
%% -*- erlang -*-
%%! -noinput -pa ./ebin -pa deps/getopt/ebin

-define(OPTS,
        [
         {help, undefined, "help", boolean,
          "Display usage information and exit"},

         {host, $h, "host", {string, "localhost"},
          "MQTT server hostname or IP address"},
         {port, $p, "port", {integer, 1883},
          "MQTT server port number"},
         {password, $P, "passwd", {string, "guest"},
          "Password for authentication"},
         {username, $u, "user", {string, "guest"},
          "Username for authentication"},
         {keep_alive, $k, "keepalive", {integer, 60},
          "Period for keep-alive ping, in seconds"},
         {client_id, $i, "id", string,
          "Client ID to use for session"},
         {unclean, $c, "disable-clean-session", {boolean, false},
          "Disable clean session"},

         {qos_level, $q, "qos", {integer, 0},
          "QoS for subscriptions"},
         {topic, $t, "topic", string,
          "A topic to which to subscribe"}
        ]).

main(Argv) ->
    {ok, {Opts, _}} = getopt:parse(?OPTS, Argv),
    case proplists:get_value(help, Opts) of
        true ->
            ScriptPath = escript:script_name(),
            Script = filename:basename(ScriptPath),
            getopt:usage(?OPTS, Script),
            halt(0);
        _ ->
            ok
    end,
    [Host, Port, Unclean] =
        [proplists:get_value(K, Opts) || K <- [host, port, unclean]],
    ConnectOpts0 = [O || O <- Opts, erlmqtt:is_connect_option(O)],
    ConnectOpts = [{clean_session, not Unclean} | ConnectOpts0],
    {ok, C} = case Unclean of
                  false ->
                      erlmqtt:open_clean({Host, Port}, ConnectOpts);
                  true ->
                      erlmqtt:open({Host, Port}, ConnectOpts)
              end,

    QoS = erlmqtt:qos_symbol(proplists:get_value(qos_level, Opts)),
    Topics = proplists:get_all_values(topic, Opts),
    io:format("Subscribing to ~tp~n", [Topics]),
    erlmqtt:subscribe(C, [{T, QoS} || T <- Topics]),
    recv().

recv() ->
    {_T, Msg} = erlmqtt:recv_message(),
    io:format("~s~n", [Msg]),
    recv().
